<?php

/**
 * payment.php
 *
 * @copyright 2018 opencart.cn
 *
 * All Rights Reserved
 * @link http://guangdawangluo.com
 *
 * @author StifferChen <chenlin@opencart.cn>
 * @created 2018-05-15 17:49
 * @modified 2018-05-15 17:49
 */
class ControllerAccountComment extends Controller
{
    private $error = array();

    public function __construct($registry)
    {
        parent::__construct($registry);
        if (!$this->customer->isLogged()) {
            $this->session->data['redirect'] = uriLink('account/comment');
            $this->response->redirect(uriLink('account/login'));
        }
        $this->load->language('account/comment');
        $this->load->model('account/order');
        $this->load->model('catalog/product');
        $this->load->model('checkout/order');
        $this->load->model('catalog/product');
        $this->load->model('account/comments');
    }

    public function delete()
    {
        $id = get('id');
        if ($id) {
            $this->model_account_comments->deleteComment(get('id'));
            $url = '';
            if (get('filter_order_id')) {
                $url .= get('filter_order_id');
            }
            if (get('filter_rating')) {
                $url .= get('filter_rating');
            }
            if (get('filter_date_created')) {
                $url .= get('filter_date_created');
            }
            if (get('filter_date_modified')) {
                $url .= get('filter_date_modified');
            }
            if (get('filter_status')) {
                $url .= get('filter_status');
            }
            if (get('page')) {
                $url .= get('page');
            }
            $this->session->data['success'] = trans('text_delete_success');
            redirect(uriLink('account/comment', $url));
        }
        redirect(uriLink('account/comment'));
    }

    public function index()
    {
        $data['heading_title'] = trans('title_product_comment');
        $this->document->setTitle(trans('title_product_comment'));

        $data['breadcrumbs'][] = array(
            'text' => trans('text_account'),
            'href' => uriLink('account/account')
        );
        $data['breadcrumbs'][] = array(
            'text' => trans('text_comment_title'),
            'href' => uriLink('account/comment')
        );

        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        } else {
            $filter_order_id = '';
        }
        if (isset($this->request->get['filter_rating'])) {
            $filter_rating = $this->request->get['filter_rating'];
        } else {
            $filter_rating = '';
        }
        if (isset($this->request->get['filter_date_created'])) {
            $filter_date_created = $this->request->get['filter_date_created'];
        } else {
            $filter_date_created = '';
        }
        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        } else {
            $filter_date_modified = '';
        }
        if (isset($this->request->get['filter_status'])) {
            $filter_status = $this->request->get['filter_status'];
        } else {
            $filter_status = '';
        }

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $limit = 10;

        $data['comments'] = array();
        $filter_data = array(
            'filter_order_id' => $filter_order_id,
            'filter_rating' => $filter_rating,
            'filter_date_created' => $filter_date_created,
            'filter_date_modified' => $filter_date_modified,
            'filter_status' => $filter_status,
            'start' => ($page - 1) * $limit,
            'limit' => $limit
        );
        $comments_total = $this->model_account_comments->commentsTotal();
        $results = $this->model_account_comments->getComments($filter_data);
        if ($results) {
            foreach ($results as $result) {
                $data['comments'][] = array(
                    'id' => $result['id'],
                    'product_name' => $result['product_name'],
                    'product_model' => $result['product_model'],
                    'rating' => $result['rating'],
                    'date_created' => $result['date_created'],
                    'date_modified' => $result['date_modified'],
                    'edit' => uriLink('account/comment/edit', 'id=' . $result['id']),
                    'delete' => uriLink('account/comment/delete', 'id=' . $result['id'])
                );
            }
        }

        if (isset($this->request->post['selected'])) {
            $data['selected'] = (array)$this->request->post['selected'];
        } else {
            $data['selected'] = array();
        }

        if (isset($this->session->data['success'])) {
            $data['success'] = $this->session->data['success'];

            unset($this->session->data['success']);
        } else {
            $data['success'] = '';
        }

        $data['filter_order_id'] = $filter_order_id;
        $data['filter_rating'] = $filter_rating;
        $data['filter_date_created'] = $filter_date_created;
        $data['filter_date_modified'] = $filter_date_modified;
        $data['filter_status'] = $filter_status;

        $url = '';
        if (isset($this->request->get['filter_order_id'])) {
            $url .= $this->request->get['filter_order_id'];
        }

        if (isset($this->request->get['filter_rating'])) {
            $url .= $this->request->get['filter_rating'];
        }

        if (isset($this->request->get['filter_date_created'])) {
            $url .= $this->request->get['filter_date_created'];
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $url .= $this->request->get['filter_date_modified'];
        }

        if (isset($this->request->get['filter_status'])) {
            $url .= $this->request->get['filter_status'];
        }

        $pagination = new Pagination();
        $pagination->total = $comments_total;
        $pagination->page = $page;
        $pagination->limit = $limit;
        $pagination->url = $this->url->link('account/comment', $url . '&page={page}', true);

        $data['pagination'] = $pagination->render();

        $data['results'] = sprintf($this->language->get('text_pagination'), ($comments_total) ? (($page - 1) * $limit) + 1 : 0, ((($page - 1) * $limit) > ($comments_total - $limit)) ? $comments_total : ((($page - 1) * $limit) + $this->config->get('config_limit_admin')), $comments_total, ceil($comments_total / $limit));

        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        $this->response->setOutput($this->load->view('account/comment_list', $data));
    }

    public function edit()
    {
        if (!get('id')) {
            redirect(uriLink('account/comment'));
        }
        $comment = $this->model_account_comments->getComment(get('id'));
        if (!$comment) {
            redirect(uriLink('account/comment'));
        }

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
            $post_data = array(
                'rating' => post('rating'),
                'comments' => post('comments'),
                'images' => post('images')
            );
            $this->model_account_comments->editComments(get('id'), $post_data);
            $this->session->data['success'] = $this->language->get('text_edit_success');
            $this->response->redirect(uriLink('account/comment'));
        }

        setTitle(trans('text_edit'));
        $data['heading_title'] = trans('text_edit');

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_account'),
            'href' => uriLink('account/account')
        );
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_comment_title'),
            'href' => uriLink('account/comment')
        );
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_edit'),
            'href' => uriLink('account/comment/edit', 'id=' . get('id'))
        );

        $data['rating'] = $comment['rating'];
        if (post('rating')) {
            $data['rating'] = post('rating');
        }

        $data['comments'] = $comment['comments'];
        if (post('comments')) {
            $data['comments'] = post('comments');
        }

        $images = $comment['images'];
        if (post('images')) {
            $images = post('images');
        }

        $data['images'] = array();
        if ($images) {
            foreach ($images as $image) {
                if (is_file(DIR_IMAGE . $image)) {
                    $data['images'][] = array(
                        'image' => resizeImage($image),
                        'src' => $image
                    );
                }
            }
        }

        $data['action'] = uriLink('account/comment/edit', 'id=' . get('id'));
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['column_right'] = $this->load->controller('common/column_right');
        $data['content_top'] = $this->load->controller('common/content_top');
        $data['content_bottom'] = $this->load->controller('common/content_bottom');
        $data['footer'] = $this->load->controller('common/footer');
        $data['header'] = $this->load->controller('common/header');

        $this->response->setOutput($this->load->view('account/comment_form', $data));
    }

    public function write()
    {
        $order_id = get('order_id');
        $product_id = get('product_id');
        $error = false;
        $text_error = '';

        if (!$order_id || !$product_id) {
            $error = true;
            $text_error = trans('error_params');
        } else {
            $customer_order = $this->model_account_order->getCustomerOrderProduct($order_id, $product_id);
            if (!$customer_order) {
                $error = true;
                $text_error = trans('error_permission');
            } else {
                $order_info = $this->model_account_order->getOrder($order_id);
                $order_status_id = $order_info['order_status_id'];
                if (!in_array($order_status_id, $this->config->get('config_complete_status'))) {
                    $error = true;
                    $text_error = trans('error_order_status');
                }
            }
        }

        if ($error) {

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_account'),
                'href' => uriLink('account/account')
            );
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_comment'),
                'href' => uriLink('account/comment')
            );

            $this->document->setTitle(trans('heading_title'));
            $data['heading_title'] = trans('heading_title');
            $data['continue'] = $this->url->link('common/home');
            $data['text_error'] = $text_error;

            $this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . ' 404 Not Found');

            $data['column_left'] = $this->load->controller('common/column_left');
            $data['column_right'] = $this->load->controller('common/column_right');
            $data['content_top'] = $this->load->controller('common/content_top');
            $data['content_bottom'] = $this->load->controller('common/content_bottom');
            $data['footer'] = $this->load->controller('common/footer');
            $data['header'] = $this->load->controller('common/header');

            $this->response->setOutput($this->load->view('error/not_found', $data));
        } else {

            $order_info = $this->model_account_order->getOrder($order_id);
            $product_info = $this->model_checkout_order->getOrderProduct($order_id, $product_id);
            $product_name = $product_info['name'];
            $product_model = $product_info['model'];
            $product_quantity = $product_info['quantity'];
            $catalog_product = $this->model_catalog_product->getProduct($product_id);
            $product_image = resizeImage($catalog_product['image'], 300, 300);
            $product_price = formatCurrency($product_info['price'], $order_info['currency_code']);

            if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
                $post_data = array(
                    'order_id' => $order_id,
                    'product_id' => $product_id,
                    'product_name' => $product_name,
                    'product_model' => $product_model,
                    'rating' => post('rating'),
                    'comments' => post('comments'),
                    'images' => post('images')
                );
                $this->model_account_comments->addComments($post_data);
                $this->session->data['success'] = $this->language->get('text_success');
                $this->response->redirect(uriLink('account/comment'));
            }

            if (isset($this->error['warning'])) {
                $data['error_warning'] = $this->error['warning'];
            } else {
                $data['error_warning'] = '';
            }

            $data['product'] = array(
                'name' => $product_name . '&nbsp;' . $product_model,
                'price' => $product_price,
                'link' => uriLink('product/product', 'product_id=' . $product_id),
                'image' => $product_image
            );
            setTitle(sprintf(trans('text_comment'), $product_name));

            $data['breadcrumbs'][] = array(
                'text' => trans('text_account'),
                'href' => uriLink('account/account')
            );
            $data['breadcrumbs'][] = array(
                'text' => trans('text_comment_title'),
                'href' => uriLink('account/comment')
            );
            $data['breadcrumbs'][] = array(
                'text' => $product_name,
                'href' => uriLink('account/comment/write', 'order_id=' . $order_id . '&product_id=' . $product_id)
            );

            $data['comments'] = '';
            if (post('comments')) {
                $data['comments'] = post('comments');
            }

            $data['rating'] = '';
            if (post('rating')) {
                $data['rating'] = post('rating');
            }

            $data['images'] = array();

            if (post('images')) {
                foreach (post('images') as $image) {
                    $data['images'][] = array(
                        'image' => resizeImage($image),
                        'src' => $image
                    );
                }
            }

            $data['heading_title'] = sprintf(trans('text_comment'), $product_name);

            $data['action'] = uriLink('account/comment/write', 'order_id=' . $order_id . '&product_id=' . $product_id);
            $data['column_left'] = $this->load->controller('common/column_left');
            $data['column_right'] = $this->load->controller('common/column_right');
            $data['content_top'] = $this->load->controller('common/content_top');
            $data['content_bottom'] = $this->load->controller('common/content_bottom');
            $data['footer'] = $this->load->controller('common/footer');
            $data['header'] = $this->load->controller('common/header');

            $this->response->setOutput($this->load->view('account/comment_form', $data));
        }
    }

    public function upload()
    {
        $file = $_FILES ? $_FILES[array_keys($_FILES)[0]] : array();
        if (!$file) {
            $json = array(
                'code' => 0,
                'msg' => $this->trans('error_empty_upload')
            );
        } else {
            if (!checkExtensions('fileinfo')) {
                $json = array(
                    'code' => 0,
                    'msg' => $this->trans('error_not_extension')
                );
            } else {
                $tmp_file = $file['tmp_name'];
                $arrow_type = array('image/png', 'image/jpeg', 'image/jpg');
                if (!checkFileType($tmp_file, $arrow_type)) {
                    $json = array(
                        'code' => 0,
                        'msg' => trans('error_file_type')
                    );
                } else {
                    $file_size = $file['size'];
                    if ($file_size > UPLOAD_SIZE_LIMIT) {
                        $json = array(
                            'code' => 0,
                            'msg' => trans('error_file_size')
                        );
                    } else {
                        $input_path = 'customer/customer_' . $this->customer->getId() . '/comments/' . date('Ymd', time());
                        $file_path = 'catalog/' . $input_path;
                        $path = DIR_IMAGE . $file_path;
                        checkPath($path);
                        $file_prefix = 'comments_' . time() . str_replace(' ', '', str_replace('.', '', microtime()));
                        $file_name_arr = explode('.', $file['name']);
                        $file_suffix = $file_name_arr[count($file_name_arr) - 1];
                        $file_name = $file_prefix . '.' . $file_suffix;
                        $return_path = $file_path . '/' . $file_name;
                        @move_uploaded_file($tmp_file, $path . '/' . $file_name);
                        if (is_file($path . '/' . $file_name)) {
                            $json = array(
                                'code' => 1,
                                'image' => resizeImage($file_path . '/' . $file_name),
                                'url' => $return_path
                            );
                        } else {
                            $json = array(
                                'code' => 0,
                                'msg' => trans('error_remove')
                            );
                        }
                    }
                }
            }
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    protected function validateForm()
    {
        if (!utf8_strlen($this->request->post['comments'])) {
            $this->error['warning'] = trans('error_empty_comments');
        }
        return !$this->error;
    }
}